<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px" style="height: 300px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类编码" prop="categoryNo">
              <el-input v-model="formData.categoryNo" placeholder="请输入分类编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="formData.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="父级分类" prop="parentId">
              <treeselect v-model="formData.parentId" :options="parentCategoryList" :normalizer="normalizer" placeholder="请选择父级分类" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as MaterialCategoryApi from '@/api/basic/materialcategory';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "MaterialCategoryForm",
  components: { Treeselect },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        categoryNo: undefined,
        categoryName: undefined,
        parentId: undefined,
      },
      // 表单校验
      formRules: {},
      // 父级分类列表（树形结构）
      parentCategoryList: []
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id, parentId) {
      this.dialogVisible = true;
      this.reset();
      // 加载父级分类列表
      await this.loadParentCategoryList();

      // 如果指定了父级ID，预先设置
      if (parentId) {
        this.formData.parentId = parentId;
      }

      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await MaterialCategoryApi.getMaterialCategory(id);
          this.formData = res.data;
          this.dialogTitle = "修改物料分类";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增物料分类";
      }
    },

    /** 加载父级分类列表 - 获取所有分类并构建树形结构 */
    async loadParentCategoryList() {
      try {
        // 获取所有分类数据，不限制parentId
        const params = {
          pageNo: 1,
          pageSize: 100, // 设置足够大的pageSize以获取所有分类
        };
        // 删除可能存在的parentId参数，确保查询所有数据
        delete params.parentId;
        const res = await MaterialCategoryApi.getMaterialCategoryPage(params);

        // 获取数据，确保数据是数组
        const allData = Array.isArray(res?.data) ? res.data : [];
        console.log('原始分类数据:', allData);

        // 使用优化的buildTree方法构建树形结构
        const treeData = this.handleTree(allData, 0);
        console.log('构建的树形结构:', treeData);

        // 添加一个"无"选项作为顶级选项
        this.parentCategoryList = [{
          id: 0,
          categoryName: '无',
          children: treeData
        }];
      } catch (error) {
        console.error('获取父级分类列表失败:', error);
        this.parentCategoryList = [{ id: 0, categoryName: '无', children: [] }];
      }
    },

    /** 树形选择器数据格式化 */
    normalizer(node) {
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await MaterialCategoryApi.updateMaterialCategory(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await MaterialCategoryApi.createMaterialCategory(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        categoryNo: undefined,
        categoryName: undefined,
        parentId: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
